package com.hbnu.web;

import com.hbnu.entity.Folder;
import com.hbnu.entity.UserFile;
import com.hbnu.entity.User;
import com.hbnu.enums.Status;
import com.hbnu.service.FunctionService;
import com.hbnu.service.UserService;
import com.hbnu.tools.PrintTool;
import com.hbnu.tools.UserFileTool;

import java.io.*;
import java.util.Map;
import java.util.Properties;
import java.util.function.BiConsumer;
import java.util.function.Consumer;

import static com.hbnu.tools.PrintTool.*;
import static com.hbnu.tools.ScannerTool.nextLine;

public class Client {
    public UserService userService=new UserService();
    //必要参数
    public static Map<Integer, UserFile> idUserFileMap;
    public static Map<String, Integer> pathIdMap;
    public static User user;
    public static StringBuilder tip;
    public static Folder folder;
    public static int startPath;
    public static int endPath;
    public static String  configPath;
    public static Properties properties = new Properties();

    //配置文件加载
    private void config(){
        String path=new File("").getAbsolutePath();
        configPath = new File("").getAbsolutePath()+"\\config.properties";
        try (InputStream input = new FileInputStream(configPath)) {
            properties.load(input);
            Status.host=properties.getProperty("host");
            Status.port=Integer.parseInt(properties.getProperty("port"));
            Status.ServerPath=properties.getProperty("ServerPath");
            if("true".equals(properties.getProperty("is_first"))){
                initPath(path);
            }
            Status.def_ClientPath = properties.getProperty("def_ClientPath");
            Status.ftf_SavePath = properties.getProperty("ftf_SavePath");
            Status.http_SavePath = properties.getProperty("http_SavePath");

        } catch (IOException e) {
            println("找不到配置文件！");
            System.exit(-1);
        }
    }
    //初始化地址
    private void initPath(String prePath){
        userService.set1(prePath+"\\file\\client");
        userService.set2(prePath+"\\file\\ftf");
        userService.set3(prePath+"\\file\\http");
        userService.updateProperties0("is_first","false");
    }
    
    public void start(){
        //检查配置文件 获得配置文件地址
        config();
        //初始化
        init();
        while (true){
            try {
                //已去除前后空白
                String line = nextLine(tip);
                String[] words = line.split("\\s+");
                //根据长度查找
                if (FunctionService.cmdSet.contains(words[0])) {
                    switch (words.length) {
                        case 1 -> {
                            Runnable function = FunctionService.cmdMap.get(words[0]);
                            if (null != function) {
                                function.run();
                            }
                        }
                        case 2 -> {
                            Consumer<String> function = FunctionService.oneMap.get(words[0]);
                            if (null != function) {
                                function.accept(words[1]);
                            }
                        }
                        default -> {
                            BiConsumer<String, String> function = FunctionService.twoMap.get(words[0]);
                            if (null != function) {
                                function.accept(words[1], words[2]);
                            }
                        }
                    }
                }
                //命令不存在
                else {
                    error(line, Status.NO_CMD);
                }
            }catch (Exception e){
                println(e.getMessage());
            }
        }
    }

    void init(){
        initPrint();
        print("login/register: ");
        String s = nextLine();
        //登录
        if(s.isEmpty()){
            logIn();
        }else {
            register();
            logIn();
        }
    }
    void logIn(){
        while (true) {
            print("login: ");
            String userName = nextLine();
            if(userName.isEmpty()) continue;
            //获得了用户名
            String password = getPassword();
            if(password.isEmpty()) {
                logonError(Status.NULL_PASS);
                continue;
            }
            //登录成功，获取用户类型
            if((user= userService.check(userName,password))!=null) {
                user.setName(userName);
                //登录成功,获取文件夹、获取父名称
                logonInit();
                //更新登录时间
                userService.updateTime(user.getUid());
                break;
            }
            println("用户不存在！");
        }
        print("waiting...\r");
        FunctionService.init();
        welcome(user);
    }
    //获取密码，在控制台隐藏状态
    String getPassword(){
        String password;
        print("Password: ");
        Console console = System.console();
        if (console != null) {
            char[] passwordArray = console.readPassword();
            password = new String(passwordArray);
        }else password = nextLine();

        return password;
    }
    //数据初始化
    void logonInit(){
        int rootId=user.getFolder_id();
        //获取文件夹Tree
        idUserFileMap=userService.getUserFileMap(user.getUid(),rootId);
        //没有子内容 ，新键账号
        if(idUserFileMap.isEmpty()){
            idUserFileMap.put(rootId,new UserFile(rootId,-1,"~",-1,false,"~"));
        }else {
            //设置根id名称
            UserFile userFile = idUserFileMap.get(rootId);
            userFile.setFname("~");
            userFile.setPath("~");
        }
        pathIdMap = UserFileTool.getPathMap(rootId,idUserFileMap);

        //路径初始化
        folder=new Folder();
        folder.setPath("~");
        folder.setFid(rootId);
        //初始化tip
        tip =new StringBuilder();
        tip.append("[").append("HBNU").append("@").append(user.getName()).append(" ");
        //记录文件名长度
        startPath= tip.length();
        endPath=startPath+1;
        tip.append("~").append("]").append("# ");
    }
    //注册方法
    void register(){
        while (true) {
            print("UserName: ");
            String userName = nextLine();
            //点错了直接登录
            if (userName.isEmpty()) return;
            //账号检查
            if (userName.length() < 3) {
                println("用户名至少为3位数");
                continue;
            }
            if(userService.checkUser(userName)){
                println("用户名已存在");
                continue;
            }
            String pwd, pwd1;
            while (true) {
                pwd = nextLine("password: ");
                if (pwd.length() < 6) {
                    println("密码至少为6位数");
                    continue;
                }
                pwd1 = nextLine("password: ");
                if (!pwd.equals(pwd1)) {
                    println("密码不一致!");
                    continue;
                }
                break;
            }
            userService.register(userName, pwd);
            println("注册成功! ");
            return;
        }
    }
}
